<?php
// Serves index.html with page-specific SEO tags in <head>. Same HTML for
// every visitor (no bot detection); React takes over in the browser.
const SITE = 'https://sofiaco.fr';
// The deploy script exports VITE_TESTING_API/VITE_ECOM_TYPE and writes them
// into .htaccess as SetEnv. Fall back to production only when PHP has no env.
$seoApi = getenv('VITE_TESTING_API') ?: ($_SERVER['VITE_TESTING_API'] ?? '');
$seoEcom = getenv('VITE_ECOM_TYPE') ?: ($_SERVER['VITE_ECOM_TYPE'] ?? '');
define('API', $seoApi ?: 'https://backapi.leonardo-service.com/api/sofiadis/sofiaco');
define('ECOM', $seoEcom ?: 'sofiaco');
define('DEFAULT_IMG', SITE . '/og-default.jpg');

header('Content-Type: text/html; charset=UTF-8');
header('Cache-Control: no-cache');
$html = file_get_contents(__DIR__ . '/index.html');
$path = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/') ?: '/';
if ($path === '/') $path = '/main';

// Product lists / categories: ?page=N, N >= 2, gets its own canonical and title.
$listPage = preg_match('#^(/main/products|/bestsellers|/nouveautes|/main/brands|/main/collaborators|/main/cp/.+)$#', $path)
    && is_string($_GET['page'] ?? null) && ctype_digit($_GET['page'])
    ? max(1, (int)$_GET['page']) : 1;
$listQuery = $listPage > 1 ? '?page=' . $listPage : '';

// GET from the API with a 1-hour file cache. null = API unreachable.
function api(string $endpoint): ?array {
    $file = sys_get_temp_dir() . '/sofiaco_seo_' . md5($endpoint) . '.json';
    if (is_file($file) && filemtime($file) > time() - 3600) {
        return json_decode(file_get_contents($file), true);
    }
    $json = @file_get_contents(API . $endpoint, false,
        stream_context_create(['http' => ['timeout' => 3, 'ignore_errors' => true]]));
    $data = $json === false ? null : json_decode($json, true);
    if (!is_array($data)) return null;
    // Only cache real answers: an error (e.g. a 429) must not stick for an hour.
    if (str_contains($http_response_header[0] ?? '', ' 200')) file_put_contents($file, $json);
    return $data;
}
function clean($s, int $max = 0): string {
    $s = trim(preg_replace('/\s+/u', ' ', strip_tags(html_entity_decode((string)$s))));
    return $max ? mb_substr($s, 0, $max) : $s;
}
function ownSiteText($s): string {
    return is_string($s) && $s !== '' && !preg_match('/hanoot|hanout/iu', $s) ? $s : '';
}
function findById(?array $list, int $id): ?array {
    foreach ($list ?? [] as $row) if ((int)($row['id'] ?? 0) === $id) return $row;
    return null;
}
function gtin($code): array {
    $c = trim((string)$code);
    if (!preg_match('/^(\d{8}|\d{12,14})$/', $c)) return [];
    $d = array_map('intval', str_split($c));
    $check = array_pop($d);
    $sum = 0;
    foreach (array_reverse($d) as $i => $n) $sum += $n * ($i % 2 ? 1 : 3);
    return (10 - $sum % 10) % 10 === $check ? ['gtin' . strlen($c) => $c] : [];
}
// Books are identified by family, Amazon classification, or a 978/979 ISBN barcode.
function isBook(array $a): bool {
    $family = $a['article_famille'] ?? [];
    $name = strtolower(trim((string)($family['type_nom'] ?? $family['code'] ?? '')));
    $barcode = trim((string)($a['_code_barre'] ?? ''));
    return ($name === 'livre' || $name === 'livres'
        || ($family['code_fiscal_amazon_mp'] ?? '') === 'A_BOOKS_GEN'
        || preg_match('/^97[89][0-9]{10}$/', $barcode) === 1);
}
function trimU(string $s): string {
    return preg_replace('/(*UCP)^\s+|\s+$/u', '', $s);
}
function slugTail(string $s): string {
    $s = preg_replace('/(*UCP)[^a-z0-9\s-]/u', '', $s);
    $s = preg_replace('/(*UCP)\s+/u', '-', $s);
    return trim(preg_replace('/-+/', '-', $s), '-');
}
// PHP twin of src/utils/slugify.js.
function slugNew(string $s): string {
    $s = str_replace(['œ', 'æ'], ['oe', 'ae'], mb_strtolower(trimU($s)));
    $s = class_exists('Normalizer')
        ? preg_replace('/[\x{0300}-\x{036F}]/u', '', Normalizer::normalize($s, Normalizer::FORM_D))
        : strtr($s, ['à'=>'a','á'=>'a','â'=>'a','ã'=>'a','ä'=>'a','å'=>'a','ç'=>'c','è'=>'e','é'=>'e','ê'=>'e','ë'=>'e',
            'ì'=>'i','í'=>'i','î'=>'i','ï'=>'i','ñ'=>'n','ò'=>'o','ó'=>'o','ô'=>'o','õ'=>'o','ö'=>'o',
            'ù'=>'u','ú'=>'u','û'=>'u','ü'=>'u','ý'=>'y','ÿ'=>'y']);
    return slugTail(preg_replace("/['’]/u", '-', $s));
}
function oldSlugMap(array $names): array {
    $new = [];
    foreach ($names as $n) if (is_string($n) && ($s = slugNew($n)) !== '') $new[$n] = $s;
    $map = [];
    foreach ($new as $n => $s) {
        $olds = [slugTail(mb_strtolower(trimU($n))), mb_strtolower(preg_replace('/(*UCP)\s+/u', '-', trimU($n)))];
        foreach ($olds as $old) {
            if ($old !== '' && $old !== $s && !in_array($old, $new, true)) $map[$old] = $s;
        }
    }
    return $map;
}
function productPath(array $a): string {
    $s = fn($t, $p) => ($v = slugNew((string)$t)) !== '' ? $v : $p;
    return '/cp/' . $s($a['article_famille']['parent']['nom'] ?? '', 'category')
        . '/' . $s($a['article_famille']['type_nom'] ?? '', 'subcategory')
        . '/' . $s($a['article_sous_categorie']['nom'] ?? '', 'sb')
        . '/' . $s($a['designation'] ?? '', 'product')
        . '/' . $a['id'];
}
// BreadcrumbList matching the product hierarchy used by the storefront URLs.
function productBreadcrumb(array $a, string $url): array {
    $parent = $a['article_famille']['parent'] ?? null;
    $family = $a['article_famille'] ?? null;
    $sub = $a['article_sous_categorie'] ?? null;
    $parentName = $parent['nom'] ?? '';
    $familyName = $family['type_nom'] ?? ($family['nom'] ?? '');
    $items = [['name' => 'Accueil', 'item' => SITE . '/main']];

    if ($parentName !== '' && !empty($parent['id'])) {
        $items[] = [
            'name' => clean($parentName),
            'item' => SITE . '/main/cp/' . slugNew($parentName) . '/' . $parent['id'],
        ];
    }
    if ($parentName !== '' && $familyName !== '' && !empty($family['id'])) {
        $items[] = [
            'name' => clean($familyName),
            'item' => SITE . '/main/cp/' . slugNew($parentName) . '/' . slugNew($familyName) . '/' . $family['id'],
        ];
    }
    if ($parentName !== '' && $familyName !== '' && !empty($sub['id']) && !empty($sub['nom'])) {
        $items[] = [
            'name' => clean($sub['nom']),
            'item' => SITE . '/main/cp/' . slugNew($parentName) . '/' . slugNew($familyName) . '/' . slugNew($sub['nom']) . '/' . $sub['id'],
        ];
    }
    $items[] = ['name' => clean($a['designation'] ?? ''), 'item' => $url];

    return [
        '@context' => 'https://schema.org',
        '@type' => 'BreadcrumbList',
        'itemListElement' => array_map(
            fn($item, $index) => [
                '@type' => 'ListItem',
                'position' => $index + 1,
                'name' => $item['name'],
                'item' => $item['item'],
            ],
            $items,
            array_keys($items)
        ),
    ];
}
function resizedImage(string $url, int $w): string {
    if (!str_starts_with($url, 'https://sofiadis.leonardo-service.com/modules/sofiadis/files/')) return $url;
    $enc = strtr(rawurlencode($url), ['%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')']);
    return "/img.php?src=$enc&w=$w";
}
function resizedSrcSet(string $url, array $widths = [400, 800, 1200]): string {
    if (resizedImage($url, $widths[0]) === $url) return $url;
    return implode(', ', array_map(fn($w) => resizedImage($url, $w) . " {$w}w", $widths));
}
const PRODUCT_IMAGE_SIZES = '(max-width: 950px) 60vw, 20vw';
function withPageNumber(string $title, int $page): string {
    if ($page <= 1) return $title;
    if (!preg_match("#(?:\s*[|:/,–—-]\s*|\s+)sofiaco\s*$#iu", $title, $m, PREG_OFFSET_CAPTURE) || $m[0][1] === 0) {
        return "$title – page $page";
    }
    return substr($title, 0, $m[0][1]) . " – page $page" . substr($title, $m[0][1]);
}
function withSiteName(string $title): string {
    return preg_match('/sofiaco/iu', $title) ? $title : "$title | Sofiaco";
}

$page = null;      // ['title','desc','image','url','type','price','jsonld']
$notFound = false;
$a = null;
$c = null;

// Product: /cp/cat/sub/subsub/product-slug/{id}[/affiliate-token]
if (preg_match('#^(/cp/[^/]+/[^/]+/[^/]+/[^/]+/(\d+))(?:/[^/]+)?$#', $path, $m)) {
    // The API answers 500 (not 404) for 10+ digit ids, which used to leave the
    // page at HTTP 200 without a noindex. Reject them before the request.
    if (strlen($m[2]) > 9) {
        $notFound = true;
    } else {
        // user_id=null matches the storefront's guest request (BookDetailsPage);
        // without it the API returns a different discount and the JSON-LD price
        // no longer matches what the page displays.
        $a = api('/articles?ecom_type=' . ECOM . '&id=' . $m[2] . '&user_id=null');
        // [] = no such id; {"error":...} = the API rejected the id.
        // null = API unreachable: leave the page alone rather than 404 a real product.
        if (is_array($a) && empty($a['designation'])) {
            $notFound = true;
        } elseif (!empty($a['designation'])) {
            $price = (float)($a['_prix_public_ttc'] ?? 0) * (1 - (float)($a['discount'] ?? 0) / 100);
            $img   = $a['articleimage'][0]['link'] ?? DEFAULT_IMG;
            $page  = [
                'title' => clean(ownSiteText($a['meta_title'] ?? '') ?: $a['designation']),
                'desc'  => clean(ownSiteText($a['meta_description'] ?? '') ?: ownSiteText($a['descriptif'] ?? '') ?: $a['designation'], 155),
                'image' => $img, 'url' => SITE . productPath($a), 'type' => 'product',
                'price' => number_format($price, 2, '.', ''),
            ];
            if (!empty($a['articleimage'][0]['link']) && empty($a['variant_product']['variants'])) {
                $page['preload'] = resizedImage($a['articleimage'][0]['link'], 800);
                $page['preloadSrcset'] = resizedSrcSet($a['articleimage'][0]['link']);
            }
            $product = [
                '@context' => 'https://schema.org', '@type' => 'Product',
                'name' => clean($a['designation']),
                'description' => clean(ownSiteText($a['descriptif'] ?? '') ?: $a['designation'], 500),
                'image' => array_column($a['articleimage'] ?? [], 'link') ?: [DEFAULT_IMG],
                'sku' => (string)$a['id'],
                'offers' => ['@type' => 'Offer', 'url' => $page['url'], 'priceCurrency' => 'EUR',
                    'price' => $page['price'],
                    'availability' => (float)($a['_qte_a_terme_calcule'] ?? 0) > 0
                        ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock'],
            ];
            if (!isBook($a)) $product += gtin($a['_code_barre'] ?? '');
            $brand = $a['marque']['nom'] ?? $a['dc_isbn_editeur'] ?? $a['editor']['_nom'] ?? null;
            if ($brand) $product['brand'] = ['@type' => 'Brand', 'name' => clean($brand)];
            $page['jsonld'] = [$product, productBreadcrumb($a, $page['url'])];
        }
    }
}
// A /cp/... product URL whose id is not numeric can never resolve to a product.
elseif (preg_match('#^/cp/(?:[^/]+/){4}[^/]+(?:/[^/]+)?$#', $path)) {
    $notFound = true;
}
// Categories: /main/cp/cat/{id}, /main/cp/cat/sub/{id}, /main/cp/cat/sub/subsub/{id}
elseif (preg_match('#^/main/cp/(?:[^/]+/){1,3}(\d+)$#', $path, $m)) {
    $id = (int)$m[1];
    $depth = substr_count($path, '/') - 3; // 1 parent, 2 sub, 3 sub-sub
    $c = null;
    if ($depth === 1) {
        $c = api('/article-famille/' . $id);
        $notFound = isset($c['message']) && empty($c['nom']);
    } elseif ($depth === 2) {
        $list = api('/article-famille?ecom_type=' . ECOM);
        $c = findById($list, $id);
        $notFound = !empty($list) && array_is_list($list) && $c === null;
    } else {
        $list = api('/article-sous-categories?ecom_type=' . ECOM);
        $c = findById($list, $id);
        $notFound = !empty($list) && array_is_list($list) && $c === null;
    }
    $name = $c['nom'] ?? $c['type_nom'] ?? null;
    if ($name) {
        if ($depth === 1) {
            $segments = [$c['nom'] ?? $name];
        } elseif ($depth === 2) {
            $parents = api('/article-famille-parents?ecom_type=' . ECOM);
            $parent = findById($parents, (int)($c['b_usr_parentcategorie_id'] ?? 0));
            $segments = [$parent['nom'] ?? 'category', $c['type_nom'] ?? $name];
        } else {
            $segments = [
                $c['article_famille']['parent']['nom'] ?? 'category',
                $c['article_famille']['type_nom'] ?? 'subcategory',
                $c['nom'] ?? $name,
            ];
        }
        $url = '/main/cp/' . implode('/', array_map(fn($s) => slugNew((string)$s), $segments)) . '/' . $id;
        $page = [
            'title' => withPageNumber(clean(ownSiteText($c['meta_title'] ?? '') ?: ownSiteText($c['title_fr'] ?? '') ?: $name), $listPage),
            'desc'  => clean(ownSiteText($c['meta_description'] ?? '') ?: ownSiteText($c['description1_fr'] ?? '')
                       ?: "$name : découvrez notre sélection sur Sofiaco.", 155),
            'image' => DEFAULT_IMG, 'url' => SITE . $url . $listQuery, 'type' => 'website',
        ];
    }
}
// Brand details: /main/brands/{id}/details
elseif (preg_match('#^/main/brands/(\d+)/details$#', $path, $m)) {
    $list = api('/publishers?ecom_type=' . ECOM . '&ids[]=' . $m[1]);
    $p = is_array($list) ? ($list[0] ?? null) : null;
    if (is_array($list) && array_is_list($list) && empty($list)) {
        $notFound = true;
    } elseif (is_array($p)) {
        $name = clean(($p['meta_title'] ?? '') ?: ($p['title'] ?? '') ?: ($p['nom'] ?? ''));
        $desc = clean(($p['meta_description'] ?? '') ?: ($p['description'] ?? '') ?: ($p['biographie'] ?? ''), 155);
        if ($desc === '') {
            $desc = clean("Découvrez $name sur Sofiaco : sélection de produits, livraison rapide et paiement sécurisé.", 155);
        }
        if ($name !== '') {
            $page = [
                'title' => $name,
                'desc' => $desc,
                'image' => !empty($p['image']) ? $p['image'] : DEFAULT_IMG,
                'url' => SITE . $path,
                'type' => 'profile',
            ];
        }
    } elseif (is_array($list) && array_is_list($list)) {
        $notFound = true;
    }
}
// Collaborator details: /main/collaborators/{id}/details
elseif (preg_match('#^/main/collaborators/(\d+)/details$#', $path, $m)) {
    $list = api('/collaborators?ecom_type=' . ECOM . '&ids[]=' . $m[1]);
    $p = is_array($list) ? ($list[0] ?? null) : null;
    if (is_array($list) && array_is_list($list) && empty($list)) {
        $notFound = true;
    } elseif (is_array($p)) {
        $name = clean(($p['meta_title'] ?? '') ?: ($p['title'] ?? '') ?: ($p['nom'] ?? ''));
        $desc = clean(($p['meta_description'] ?? '') ?: ($p['biographie'] ?? '') ?: ($p['_description'] ?? ''), 155);
        if ($desc === '') {
            $desc = clean("Découvrez $name sur Sofiaco : livres, parutions et actualités.", 155);
        }
        if ($name !== '') {
            $page = [
                'title' => $name,
                'desc' => $desc,
                'image' => !empty($p['image']) ? $p['image'] : DEFAULT_IMG,
                'url' => SITE . $path,
                'type' => 'profile',
            ];
        }
    } elseif (is_array($list) && array_is_list($list)) {
        $notFound = true;
    }
}

// Static / list pages handled by this file (title/description/canonical).
if (!$page && !$notFound) {
    $static = [
        '/main' => ['Sofiaco — Librairie, parfums et produits du monde',
            'Découvrez la sélection Sofiaco : livres, parfums, beauté, épicerie et produits du monde. Livraison rapide et paiement sécurisé.'],
        '/main/products' => ['Tous les produits', 'Parcourez tout le catalogue Sofiaco : livres, parfums, beauté, épicerie et produits du monde.'],
        '/bestsellers' => ['Meilleures Ventes', 'Les livres et produits les plus vendus chez Sofiaco, sélectionnés par notre équipe et nos clients.'],
        '/nouveautes' => ['Nouveautés', 'Découvrez les dernières nouveautés Sofiaco : nouveaux livres, parfums, beauté et produits du monde.'],
        '/main/blogs' => ['Blog', 'Actualités, conseils et histoires Sofiaco : livres, culture et univers de nos auteurs.'],
        '/main/brands' => ['Marques', 'Découvrez les marques et maisons d’édition distribuées par Sofiaco.'],
        '/main/collaborators' => ['Collaborateurs', 'Découvrez les auteurs, traducteurs, illustrateurs et éditeurs qui travaillent avec Sofiaco.'],
        '/main/events' => ['Événements', 'Découvrez les événements Sofiaco : ateliers, dédicaces et rencontres culturelles.'],
        '/main/about' => ['À propos de Sofiaco', 'Découvrez Sofiaco, distributeur de livres, parfums, beauté et produits du monde.'],
        '/main/contact' => ['Contactez-nous', 'Contactez Sofiaco : questions sur une commande, un produit ou un partenariat.'],
        '/main/policies' => ['Mentions légales', 'Mentions légales, conditions et politiques du site Sofiaco.'],
    ];
    if (isset($static[$path])) {
        [$title, $desc] = $static[$path];
        $page = [
            'title' => withPageNumber($title, $listPage),
            'desc' => $desc, 'image' => DEFAULT_IMG,
            'url' => SITE . $path . $listQuery, 'type' => 'website',
        ];
    }
}

// 301 old accent-dropped / accented / navbar slugs to the current slugify form.
$names = [];
$slugSegments = 0;
if (!empty($a['designation'])) {
    $names = [$a['designation'], $a['article_famille']['parent']['nom'] ?? null,
        $a['article_famille']['type_nom'] ?? null, $a['article_sous_categorie']['nom'] ?? null];
    $slugSegments = 4;
} elseif (!empty($c['nom']) && preg_match('#^/main/cp/((?:[^/]+/){1,3})\d+$#', $path, $m)) {
    $slugSegments = substr_count($m[1], '/');
    $parents = api('/article-famille-parents?ecom_type=' . ECOM);
    $names = is_array($parents) && array_is_list($parents) ? array_column($parents, 'nom') : [];
    if ($slugSegments > 1) {
        $subs = api('/article-famille?ecom_type=' . ECOM);
        if (is_array($subs) && array_is_list($subs)) $names = array_merge($names, array_column($subs, 'type_nom'));
    }
    if ($slugSegments > 2) {
        $sscs = api('/article-sous-categories?ecom_type=' . ECOM);
        if (is_array($sscs) && array_is_list($sscs)) $names = array_merge($names, array_column($sscs, 'nom'));
    }
}
if ($names && $slugSegments > 0) {
    $map = oldSlugMap($names);
    $segments = explode('/', $path);
    $start = str_starts_with($path, '/main/cp/') ? 3 : 2;
    for ($i = $start; $i < $start + $slugSegments; $i++) {
        $seg = rawurldecode($segments[$i] ?? '');
        if (isset($map[$seg])) $segments[$i] = $map[$seg];
        elseif (preg_match('/^(.+)(-\d+)$/', $seg, $s) && isset($map[$s[1]])) $segments[$i] = $map[$s[1]] . $s[2];
    }
    $target = implode('/', $segments);
    if ($target !== $path) {
        $query = $_SERVER['QUERY_STRING'] ?? '';
        header('Location: ' . $target . ($query !== '' ? '?' . $query : ''), true, 301);
        exit;
    }
}

// ?page past the last page of a category or a known list = 404. /articles has
// no count, so ask for a page far past the end: no products, just `total`.
if ($listPage > 1 && !$notFound) {
    $filter = null;
    if ($path === '/nouveautes') $filter = 'newarrival=true';
    elseif ($path === '/bestsellers') $filter = 'sortbybestseller';
    elseif (preg_match('#^/main/cp/(?:[^/]+/){1,3}(\d+)$#', $path, $m)) {
        $filter = [1 => 'articlefamilleparent_id=', 2 => 'articlefamille_id=',
                   3 => 'b_usr_articlesouscategorie_id='][substr_count($path, '/') - 3] . $m[1];
    }
    $counted = $filter
        ? api('/articles?page=99999&' . $filter . '&ecom_type=' . ECOM)
        : ($path === '/main/products' ? api('/articles?page=99999&ecom_type=' . ECOM) : null);
    if (isset($counted['total']) && is_numeric($counted['total'])) {
        $notFound = $listPage > max(1, (int)ceil($counted['total'] / 36));
    }
}

if ($notFound) {
    http_response_code(404);
    if (!$page) {
        $page = [
            'title' => 'Page introuvable',
            'desc' => "La page que vous recherchez n'existe pas ou n'est plus disponible.",
            'image' => DEFAULT_IMG,
            'url' => SITE . $path,
            'type' => 'website',
        ];
    }
    $html = str_replace('</head>', '<meta data-rh="true" name="robots" content="noindex,nofollow" />' . "\n</head>", $html);
}
if ($page) {
    $e = fn($s) => htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
    $title = withSiteName($page['title']);
    $block  = "<title data-rh=\"true\">{$e($title)}</title>\n";
    $block .= "<meta data-rh=\"true\" name=\"description\" content=\"{$e($page['desc'])}\" />\n";
    $block .= "<link data-rh=\"true\" rel=\"canonical\" href=\"{$e($page['url'])}\" />\n";
    $block .= "<link data-rh=\"true\" rel=\"alternate\" hreflang=\"fr\" href=\"{$e($page['url'])}\" />\n";
    $block .= "<link data-rh=\"true\" rel=\"alternate\" hreflang=\"x-default\" href=\"{$e($page['url'])}\" />\n";
    $block .= "<meta data-rh=\"true\" property=\"og:type\" content=\"{$page['type']}\" />\n";
    $block .= "<meta data-rh=\"true\" property=\"og:title\" content=\"{$e($title)}\" />\n";
    $block .= "<meta data-rh=\"true\" property=\"og:description\" content=\"{$e($page['desc'])}\" />\n";
    $block .= "<meta data-rh=\"true\" property=\"og:url\" content=\"{$e($page['url'])}\" />\n";
    $block .= "<meta data-rh=\"true\" property=\"og:image\" content=\"{$e($page['image'])}\" />\n";
    if ($page['image'] === DEFAULT_IMG) {
        $block .= "<meta data-rh=\"true\" property=\"og:image:width\" content=\"1200\" />\n";
        $block .= "<meta data-rh=\"true\" property=\"og:image:height\" content=\"630\" />\n";
    }
    $block .= "<meta data-rh=\"true\" name=\"twitter:title\" content=\"{$e($title)}\" />\n";
    $block .= "<meta data-rh=\"true\" name=\"twitter:description\" content=\"{$e($page['desc'])}\" />\n";
    $block .= "<meta data-rh=\"true\" name=\"twitter:image\" content=\"{$e($page['image'])}\" />\n";
    if (!empty($page['preload'])) {
        $block .= "<link rel=\"preload\" as=\"image\" href=\"{$e($page['preload'])}\" imagesrcset=\"{$e($page['preloadSrcset'])}\""
            . " imagesizes=\"" . PRODUCT_IMAGE_SIZES . "\" fetchpriority=\"high\" />\n";
    }
    if (!empty($page['price'])) {
        $block .= "<meta data-rh=\"true\" property=\"product:price:amount\" content=\"{$page['price']}\" />\n";
        $block .= "<meta data-rh=\"true\" property=\"product:price:currency\" content=\"EUR\" />\n";
    }
    if (!empty($page['jsonld'])) {
        $block .= '<script data-rh="true" type="application/ld+json">'
            . json_encode($page['jsonld'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_HEX_TAG)
            . "</script>\n";
    }
    $start = strpos($html, '<!--seo:start-->');
    $end   = strpos($html, '<!--seo:end-->');
    if ($start !== false && $end !== false) {
        $html = substr($html, 0, $start) . $block . substr($html, $end + strlen('<!--seo:end-->'));
    }
} else {
    // Default tags: canonical and og:url still point at this page, not the home page.
    $url = htmlspecialchars(SITE . $path . $listQuery, ENT_QUOTES, 'UTF-8');
    $html = str_replace(
        ['rel="canonical" href="' . SITE . '/main"', 'property="og:url" content="' . SITE . '/main"'],
        ['rel="canonical" href="' . $url . '"', 'property="og:url" content="' . $url . '"'],
        $html
    );
}
echo $html;
